//
//  LauOpeManager.m
//  kabu
//
//  Created by XiangDongMBP on 2017/4/25.
//  Copyright © 2017年 East. All rights reserved.
//

#import "LauOpeManager.h"
#import <YYWebImage.h>
#import "ApiManager.h"
#import "XDAFNetworking.h"

@interface LauOpeManager ()

@end

static NSString * const kLaunchPropertyName = @"launchOperateImg.plist"; //!< 属性文件的名称

@implementation LauOpeManager
+ (instancetype)sharedManager {
    static LauOpeManager *sharedManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedManager = [[self alloc] init];
    });
    return sharedManager;
}
- (void)downloadLaunchOperateImg {
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiAdvertisement] parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求广告页面%@", responseObject);
        if ([responseObject[@"err_code"] integerValue] == 200) {
            NSString *imgUrl = nil;
            if ([responseObject[@"result"] isKindOfClass:[NSDictionary class]]) {
                imgUrl = responseObject[@"result"][@"advertisement_url"];
            }
            NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:[self pathForLaunchOperateImgPlist]];
            if (!(dic && [dic[@"url"] isEqualToString:imgUrl])) {
                [self downloadImgWithUrl:imgUrl];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        ;
    }];
}
- (BOOL)launchOperateImgExist {
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:[self pathForLaunchOperateImgPlist]];
    if (dic && dic[@"url"] && dic[@"imgData"]) {
        return YES;
    }
    return NO;
}
- (UIImage *)launchOperateImg {
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:[self pathForLaunchOperateImgPlist]];
    if (dic && dic[@"url"] && dic[@"imgData"]) {
        return [UIImage imageWithData:dic[@"imgData"]];
    }
    return nil;
}

#pragma mark - private methods
- (NSString *)pathForLaunchOperateImgPlist {
    NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    return [document stringByAppendingPathComponent:kLaunchPropertyName];
}

- (void)downloadImgWithUrl:(NSString *)str {
    if (![str isKindOfClass:[NSString class]] || !str.length) {
        return;
    }
    
    [[YYWebImageManager sharedManager] requestImageWithURL:[NSURL URLWithString:str] options:YYWebImageOptionShowNetworkActivity progress:nil transform:nil completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
        if (image && url) {
            NSDictionary *dic = @{@"url" : url.absoluteString,
                                  @"imgData" : UIImageJPEGRepresentation(image, 1)};
            [dic writeToFile:[self pathForLaunchOperateImgPlist] atomically:YES];
        }
    }];
}

@end
